package com.briup.demo.mapper;

import com.briup.demo.User;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;


//在程序运行时 框架会自动生成接口的实现类对象，并交给spring的IOC容器管理
@Mapper//表示这是MyBatis中的Mapper接口
public interface UserMapper {
    public void deleteByIdXML(Integer id);
    //写sql语句-查询所有用户数据
    //@select代表写的是select语句
    @Select("select * from t_user")
    public List<User> allUserList();

    //根据id查询用户
    //手动映射结果
    //@Results({@Result(column = "register_time",property = "registerTime")})
    @Select("select id,name,phone,register_time as registerTime from t_user where id = #{id}")
    public User getById(Integer id);

    //组合查询
    //查询姓张的同学，性别女，注册时间2024年11月25日10:46:05之后的，2024年11月26日10:46:57之前，结果降序
//    @Select("select * from t_user where name like '%${name}%' AND gender = ${gender} " +
//            "  AND register_time between #{startTime} AND #{endTime} " +
//            "  ORDER BY register_time DESC")
//    public List<User> getUserList(@Param("name") String name,@Param("gender") Short gender,@Param("startTime") LocalDateTime startTime,@Param("endTime") LocalDateTime endTime);
      @Select("SELECT * FROM t_user " +
          "WHERE name LIKE CONCAT('%', #{name}, '%') " +
          "AND gender = #{gender} " +
          "AND register_time BETWEEN #{startTime} AND #{endTime} " +
          "ORDER BY register_time DESC"
  )
  List<User> getUserList(
          @Param("name") String name,
          @Param("gender") Short gender,
          @Param("startTime") LocalDateTime startTime,
          @Param("endTime") LocalDateTime endTime
  );
    //根据id删除用户
    @Delete("delete from t_user where id = #{id}")
    public void deleteById(Integer id);

    //登录
    //无法防止sql注入
    //@Select("select * from t_user where username=${username} and password=${password}")
    //可以预防sql注入
    @Select("select * from t_user where name=#{name} and phone=#{phone}")

    public List<User> login(@Param("name") String name, @Param("phone") String phone);

    //新增
    //@Insert("insert into t_user (name,age,gender) values (#{name},#{age},#{gender})")
    @Options(useGeneratedKeys = true,keyProperty = "id")//要求返回主键 赋值给user对象的id属性上
    @Insert("insert into t_user (name,age,gender,phone,birthday,register_time) values (#{name},#{age},#{gender},#{phone},#{birthday},#{registerTime})")
    public void addUser(User user);

    //编辑
    @Update("update t_user set name=#{name},age=#{age},gender=#{gender},phone=#{phone} where id=#{id}")
    //@Update("update t_user set phone=#{phone} where id=#{id}")
    public void updateUser(User user);
}
